package com.parmal.proxy.handler.http;


import com.parmal.proxy.configuration.HttpProxyConfiguration;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpRequestAuthHandler extends SimpleChannelInboundHandler<HttpObject> {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestAuthHandler.class);

    private HttpProxyConfiguration configuration;

    public HttpRequestAuthHandler(HttpProxyConfiguration configuration) {
        this.configuration = configuration;
    }

    protected void messageReceived(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws
            Exception {
        logger.info("receive message =>{}",httpObject.getClass());
        if (httpObject instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) httpObject;
            boolean isSuccess = request.decoderResult().isSuccess();
            logger.info("defaultHttpRequest 解析结果=>{}",isSuccess);
            if (isSuccess) {
                HttpHeaders headers = request.headers();
                //鉴权
                CharSequence secret = headers.get(this.configuration.authHeaderKey);
                headers.remove(this.configuration.authHeaderKey);
                logger.info("密码=>{}",secret);
            }
        }
        channelHandlerContext.fireChannelRead(httpObject);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
